package com.machineapps.botesom.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.machineapps.botesom.R;
import com.machineapps.botesom.model.Button;
import com.machineapps.framework.util.Player;

public class PageButtonAdapter extends BaseAdapter {

	private Context context;

	private List<Button> buttons;

	public PageButtonAdapter(Context context, List<Button> buttons) {
		this.context = context;
		this.buttons = buttons;
	}

	public int getCount() {
		return 9;
	}

	public Object getItem(int position) {
		Object button = null;

		if (this.buttons != null && !this.buttons.isEmpty() && this.buttons.size() > position) {
			button = this.buttons.get(position);
		}

		return button;
	}

	public long getItemId(int position) {
		long id = 0;

		if (this.buttons != null && !this.buttons.isEmpty() && this.buttons.size() > position) {
			id = this.buttons.get(position).getId();
		}

		return id;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View view = new View(this.context);
		Button button = (Button) getItem(position);

		if (button != null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = inflater.inflate(R.layout.icon_button, null);

			ImageView buttonImage = (ImageView) view.findViewById(R.id.button_id);
			buttonImage.setTag(button);
			buttonImage.setOnClickListener(new ClickButtonListener());

			TextView buttonName = (TextView) view.findViewById(R.id.button_name);
			buttonName.setText(button.getName());

		}
		return view;
	}

	class ClickButtonListener implements OnClickListener {

		@Override
		public void onClick(View view) {
			Button button = (Button) view.getTag();
			int resource = context.getResources().getIdentifier(button.getSoundFileName(), "raw",
					"com.machineapps.botesom");
			Player.play(context, resource);

			view.setBackgroundResource(R.anim.button_animation);
			final AnimationDrawable animSequence = (AnimationDrawable) view.getBackground();
			animSequence.setVisible(true, false);
			animSequence.setOneShot(true);

			animSequence.stop();
			animSequence.start();

			// Animation shake = AnimationUtils.loadAnimation(context, R.anim.shake);
			// view.startAnimation(shake);
		}
	}

}